<template>
  <div>
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <i class="el-icon-document stats-icon" style="color: #409EFF;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ total }}</div>
              <div class="stats-label">变更申请总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card" @click.native="filterPending">
          <div class="stats-content">
            <i class="el-icon-time stats-icon" style="color: #E6A23C;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ pendingCount }}</div>
              <div class="stats-label">待我审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card" @click.native="filterCompleted">
          <div class="stats-content">
            <i class="el-icon-check stats-icon" style="color: #67C23A;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ completedCount }}</div>
              <div class="stats-label">已完成</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 变更申请说明 -->
    <el-alert
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    >
      <template slot="title">
        <strong>📋 变更申请说明</strong>
      </template>
      <div style="font-size: 13px; line-height: 1.8; color: #606266;">
        • <strong>不同教师间换题</strong>：原教师先审核，同意后新教师才能审核，两位都同意才能完成变更<br/>
        • <strong>同一教师内换题</strong>：学生在您的题目之间切换，您审核同意后即可完成变更<br/>
        • <strong>变更影响</strong>：跨教师变更会影响双方指导学生数，同教师内换题仅影响题目名额
      </div>
    </el-alert>

    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
        <el-form-item label="学生姓名" prop="studentName">
          <el-input
            v-model="queryParams.studentName"
            placeholder="请输入学生姓名"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="filterType" placeholder="全部" style="width: 150px" @change="handleQuery">
            <el-option label="全部" value="" />
            <el-option label="待我审核" value="pending" />
            <el-option label="待审核中" value="reviewing" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 申请列表 -->
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span class="card-title">变更申请列表</span>
      </div>

      <el-table v-loading="loading" :data="requestList" border>
        <el-table-column label="序号" type="index" width="50" align="center" />
        
        <el-table-column label="学生信息" min-width="130">
          <template slot-scope="scope">
            <div><strong>{{ scope.row.studentName }}</strong></div>
            <div style="color: #909399; font-size: 12px;">{{ scope.row.studentNo }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="原题目 → 新题目" min-width="280" show-overflow-tooltip>
          <template slot-scope="scope">
            <div style="display: flex; align-items: center;">
              <div style="flex: 1; overflow: hidden; text-overflow: ellipsis;">
                <div>{{ scope.row.oldTopicTitle }}</div>
                <div style="color: #909399; font-size: 12px;">{{ scope.row.oldTeacherName }}</div>
              </div>
              <i class="el-icon-right" style="margin: 0 10px; color: #909399;"></i>
              <div style="flex: 1; overflow: hidden; text-overflow: ellipsis;">
                <div>{{ scope.row.newTopicTitle }}</div>
                <div style="color: #909399; font-size: 12px;">{{ scope.row.newTeacherName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="变更类型" width="110" align="center">
          <template slot-scope="scope">
            <el-tag :type="isSameTeacher(scope.row) ? 'info' : getMyRoleType(scope.row)" size="small">
              {{ isSameTeacher(scope.row) ? '同教师内换题' : getMyRole(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="审核进度" min-width="200" align="center">
          <template slot-scope="scope">
            <!-- 同一教师：只显示一个步骤 -->
            <div v-if="isSameTeacher(scope.row)" style="text-align: center;">
              <el-tag 
                :type="scope.row.oldTeacherOpinion === '同意' ? 'success' : scope.row.oldTeacherOpinion === '拒绝' ? 'danger' : 'warning'"
                size="medium"
              >
                {{ getStepDesc(scope.row.oldTeacherOpinion) }}
              </el-tag>
            </div>
            <!-- 不同教师：显示两个步骤 -->
            <el-steps v-else :active="getStepActive(scope.row)" simple>
              <el-step 
                title="原教师" 
                :description="getStepDesc(scope.row.oldTeacherOpinion)"
                :status="getStepStatus(scope.row.oldTeacherOpinion)"
              ></el-step>
              <el-step 
                title="新教师" 
                :description="getStepDesc(scope.row.newTeacherOpinion)"
                :status="getStepStatus(scope.row.newTeacherOpinion)"
              ></el-step>
            </el-steps>
          </template>
        </el-table-column>
        
        <el-table-column label="最终状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.finalStatus || scope.row.status)" size="small">
              {{ scope.row.finalStatus || scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="申请时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >详情</el-button>
            <el-button
              v-if="canReview(scope.row)"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleReview(scope.row)"
              style="color: #E6A23C;"
            >审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 审核对话框 -->
    <review-dialog ref="reviewDialog" @success="getList" />

    <!-- 详情对话框 -->
    <detail-dialog ref="detailDialog" />
  </div>
</template>

<script>
import { listTeacherChangeRequests } from "@/api/system/topicChangeRequest";
import { getTeacherProfile } from "@/api/system/user";
import ReviewDialog from "./ReviewDialog";
import DetailDialog from "./DetailDialog";

export default {
  name: "ChangeRequestList",
  components: {
    ReviewDialog,
    DetailDialog
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 申请列表
      requestList: [],
      // 当前教师ID
      currentTeacherId: null,
      // 筛选类型
      filterType: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null
      }
    };
  },
  computed: {
    pendingCount() {
      return this.requestList.filter(req => this.canReview(req)).length;
    },
    completedCount() {
      return this.requestList.filter(req => req.finalStatus === '已通过' || req.finalStatus === '已拒绝').length;
    }
  },
  created() {
    this.getCurrentTeacherId();
    this.getList();
  },
  methods: {
    /** 获取当前教师ID */
    getCurrentTeacherId() {
      getTeacherProfile().then(response => {
        this.currentTeacherId = response.data.teacherId;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listTeacherChangeRequests(this.queryParams).then(response => {
        let list = response.rows;
        
        // 根据筛选类型过滤
        if (this.filterType === 'pending') {
          // 待我审核
          list = list.filter(req => this.canReview(req));
        } else if (this.filterType === 'reviewing') {
          // 待审核中（所有待审核状态的）
          list = list.filter(req => req.status === '待审核');
        } else if (this.filterType === 'approved') {
          // 已通过
          list = list.filter(req => req.finalStatus === '已通过');
        } else if (this.filterType === 'rejected') {
          // 已拒绝
          list = list.filter(req => req.finalStatus === '已拒绝');
        } else if (this.filterType === 'cancelled') {
          // 已取消
          list = list.filter(req => req.status === '已取消');
        } else if (this.filterType === 'completed') {
          // 已完成（已通过+已拒绝）
          list = list.filter(req => req.finalStatus === '已通过' || req.finalStatus === '已拒绝');
        }
        
        this.requestList = list;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置 */
    resetQuery() {
      this.filterType = '';
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 筛选待审核 */
    filterPending() {
      this.filterType = 'pending';
      this.handleQuery();
    },
    /** 筛选已完成（已通过+已拒绝） */
    filterCompleted() {
      this.filterType = 'completed';
      this.handleQuery();
    },
    /** 查看详情 */
    handleView(row) {
      this.$refs.detailDialog.open(row.requestId);
    },
    /** 审核 */
    handleReview(row) {
      const isOldTeacher = row.oldTeacherId === this.currentTeacherId;
      const isSameTeacher = this.isSameTeacher(row);
      this.$refs.reviewDialog.open(row, isOldTeacher, isSameTeacher);
    },
    /** 判断是否是同一个教师 */
    isSameTeacher(row) {
      return row.oldTeacherId === row.newTeacherId;
    },
    /** 判断是否可以审核 */
    canReview(row) {
      if (row.status !== '待审核') return false;
      
      const isOldTeacher = row.oldTeacherId === this.currentTeacherId;
      const isNewTeacher = row.newTeacherId === this.currentTeacherId;
      
      // 如果是同一个教师，只需要审核一次
      if (isOldTeacher && isNewTeacher) {
        return !row.oldTeacherOpinion;
      }
      
      if (isOldTeacher && !row.oldTeacherOpinion) {
        return true; // 原教师未审核
      }
      if (isNewTeacher && row.oldTeacherOpinion === '同意' && !row.newTeacherOpinion) {
        return true; // 原教师同意后，新教师未审核
      }
      return false;
    },
    /** 获取我的角色 */
    getMyRole(row) {
      const isOldTeacher = row.oldTeacherId === this.currentTeacherId;
      return isOldTeacher ? '原教师' : '新教师';
    },
    /** 获取角色标签类型 */
    getMyRoleType(row) {
      const isOldTeacher = row.oldTeacherId === this.currentTeacherId;
      return isOldTeacher ? 'warning' : 'success';
    },
    /** 获取步骤激活状态 */
    getStepActive(row) {
      if (row.finalStatus) return 2;
      if (row.newTeacherOpinion) return 2;
      if (row.oldTeacherOpinion) return 1;
      return 0;
    },
    /** 获取步骤描述 */
    getStepDesc(opinion) {
      if (opinion === '同意') return '已同意';
      if (opinion === '拒绝') return '已拒绝';
      return '待审核';
    },
    /** 获取步骤状态（控制颜色） */
    getStepStatus(opinion) {
      if (opinion === '同意') return 'success';  // 绿色
      if (opinion === '拒绝') return 'error';    // 红色
      return 'wait';  // 灰色
    },
    /** 状态标签类型 */
    getStatusType(status) {
      const map = {
        '待审核': 'warning',
        '已通过': 'success',
        '已拒绝': 'danger'
      };
      return map[status] || 'info';
    }
  }
};
</script>

<style scoped lang="scss">
.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  font-size: 48px;
  margin-right: 20px;
}

.stats-text {
  flex: 1;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.search-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
}

::v-deep .el-steps--simple {
  padding: 0;
  background: transparent;
}
</style>